// pages/write/write.js
/**
 * 连接设备。获取数据
 */
var snbc = require("../../utils/print-sdk.js");
Page({

  data: {
    deviceId: '',
    name: '',
    serviceId: '',
    isDisabled: true,
    services: [],
    newBoothName: '',
    sumNum: 0,
    imageSrc: '../../image/122.jpg',
    myjson: {
      "taskID": "printer_test-123",
      "label": {
        "width": 560,
        "height": 330
      },
      "data": [
       {
        "type": "qrcode",
          "x": 380,
          "y": 185,
          "content": 'DA21321321321',
          "orientation": 1,
          "level": "H",
          "model": 3,
          "width": 7,
          "comment": "运单号二维码"
       }
      ]
    },
  },

  onLoad: function(opt) {
    var that = this;

    that.setData({
      deviceId: opt.deviceId,
      name: opt.name,
      newBoothName: opt.newBoothName,
      isDisabled:opt.isDisabled
    });

  this.base64Tocanvas();
   function  MonitorBLEStatus(res) {

    if(!res.connected)
    {
      wx.showToast({
        title: opt.name+'状态改变，蓝牙连接失败，请回退页面重新连接',
        icon: 'none',
        duration: 5*1000,
        mask: true
      })
      that.setData({
        deviceId: opt.deviceId,
        name: opt.name,
        isDisabled:opt.isDisabled
      });
    }
    else{
      wx.showToast({
        title: opt.name+'连接成功',
        icon: 'none',
        duration: 5*1000,
        mask: true
      })
      that.setData({
        isDisabled:false
      });
    }
  }
    snbc.SnbcPrinter.regeisterFUN(MonitorBLEStatus)

    snbc.SnbcPrinter.connectPrinter({
      PrinterBLEid:opt.deviceId,
      success:(res) => {
        console.log(res);
      },
      fail:(res) => {
        console.log(res);
      },
      complete:(res) => {
        console.log(res);
      }
    })
  },

  closeBLEConnection: function() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    wx.showToast({
      title: '断开连接',
      icon: 'succes',
      duration: 2000,
      mask: true
    })
  },
  getDate() {
				// 获取当前日期和时间
				const now = new Date();

				// 获取年
				const year = now.getFullYear();

				// 获取月（注意：月份从 0 开始计数，所以需要加 1）
				const month = now.getMonth() + 1;

				// 获取日
				const day = now.getDate();

				// 获取时
				const hour = now.getHours();

				// 获取分
				const minute = now.getMinutes();

				// 获取秒
				const second = now.getSeconds() >= 10 ? now.getSeconds() : `0${now.getSeconds()}`;
				return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
				console.log(`当前时间：${year} 年 ${month} 月 ${day} 日 ${hour} 时 ${minute} 分 ${second} 秒`);
			},
  // 添加生成BLE打印机SDK格式数据的方法
  generatePrintDataForBLE(item) {
    console.log('🎨 开始生成BLE打印机SDK格式的打印数据...');

    if (!item) {
      throw new Error('item参数不能为空');
    }
    if (!item.barCode) {
      throw new Error('barCode字段不能为空');
    }

    const currentTime = this.getDate();

    // 根据SDK demo中的格式生成打印数据
    const blePrintData = {
      "taskID": "ltl_shipping_label-" + Date.now(),
      "label": {
        "width": 568,
        "height": 355
      },
      "data": [
                  { //logo
                  	"type": "image",
                  	"x": 15,
                  	"y": 25,
                  	"width": 40,
                  	"height": 40,
                  	"imagedata": ""
                  },
                  {
                    "type": "text",
                    "x": 58,
                    "y": 32,
                    "fontNo": 0,
                    "fontsize": 0,
                    "content": "丽尚国潮",
                    "bold": 1,
                    "setmag": 0,
                    "reverse": 0,
                    "comment": "logo标题"
                  },
                  {
                    "type": "text",
                    "x": 200,
                    "y": 36,
                    "fontNo": 0,
                    "fontsize": 0,
                    "content": "0571 86570110",
                    "bold": 1,
                    "setmag": 0,
                    "reverse": 0,
                    "comment": "logo电话"
                  },
                  { //第1条水平线
                    "type": "line",
                    "startx": 15,
                    "starty": 91,
                    "endx": 350,
                    "endy": 91,
                    "thickness": 2
                  },
                  { //第2条水平线
                    "type": "line",
                    "startx": 15,
                    "starty": 208,
                    "endx": 541,
                    "endy": 208,
                    "thickness": 2
                  },
                  { //第3条水平线
                    "type": "line",
                    "startx": 15,
                    "starty": 298,
                    "endx": 541,
                    "endy": 298,
                    "thickness": 2
                  },
                  { //第1条垂直线
                    "type": "line",
                    "startx": 350,
                    "starty": 10,
                    "endx": 350,
                    "endy": 505,
                    "thickness": 1
                  },
      
                  // 2. 二维码
                  {
                    "type": "qrcode",
                    "x": 380,
                    "y": 165,
                    "content": item.barCode || '',
                    "orientation": 1,
                    "level": "H",
                    "model": 3,
                    "width": 6,
                    "comment": "运单号二维码"
                  },
      
                  // 3. 文字信息 - 专线名称 (30px字体)
                  {
                    "type": "text",
                    "x": 70,
                    "y": 110,
                    "fontNo": 2,
                    "fontsize": 2,
                    "content": item.lineName || '',
                    "bold": 1,
                    "setmag": 2,
                    "reverse": 0,
                    "comment": "专线名称"
                  },
      
                  // 4. 网点名称 (30px字体)
                  {
                    "type": "text",
                    "x": 50,
                    "y": 155,
                    "fontNo": 2,
                    "fontsize": 2,
                    "content": item.shippingPointName || '',
                    "bold": 1,
                    "setmag": 2,
                    "reverse": 0,
                    "comment": "网点名称"
                  },
      
                  // 5. 运单号 (24px字体)
                  {
                    "type": "text",
                    "x": 390,
                    "y": 180,
                    "fontNo": 0,
                    "fontsize": 0,
                    "content": item.barCode || '',
                    "bold": 1,
                    "setmag": 0,
                    "reverse": 0,
                    "comment": "运单号"
                  },
      
                  // 6. 发货人信息 (24px字体)
                  {
                    "type": "text",
                    "x": 370,
                    "y": 230,
                    "fontNo": 2,
                    "fontsize": 2,
                    "content": "发:" + (item.consignorName || ''),
                    "bold": 0,
                    "setmag": 0,
                    "reverse": 0,
                    "comment": "发货人"
                  },
      
                  // 7. 发货人电话 (24px字体)
                  {
                    "type": "text",
                    "x": 370,
                    "y": 260,
                    "fontNo": 0,
                    "fontsize": 0,
                    "content": item.consignorTel || '',
                    "bold": 1,
                    "setmag": 0,
                    "reverse": 0,
                    "comment": "发货人电话"
                  },
      
                  // 8. 收货人信息 (36px字体，较大，限制宽度165)
                  {
                    "type": "text",
                    "x": 50,
                    "y": 230,
                    "fontNo": 0,
                    "setmag": 0,
                    "content": "收 : " + (item.consigneeLinkman || ''),
                    "bold": 1,
                    "setmag": 0,
                    "reverse": 0,
                    "comment": "收货人"
                  },
      
                  // 9. 收货人电话 (24px字体)
                  {
                    "type": "text",
                    "x": 80,
                    "y": 270,
                    "fontNo": 0,
                    "fontsize": 0,
                    "content": item.consigneeTel || '',
                    "bold": 1,
                    "setmag": 0,
                    "reverse": 0,
                    "comment": "收货人电话"
                  },
      
                  // 10. 打印时间 (24px字体)
                  {
                    "type": "text",
                    "x": 30,
                    "y": 310,
                    "fontNo": 0,
                    "fontsize": 0,
                    "content": "打印时间：",
                    "bold": 1,
                    "setmag": 0,
                    "reverse": 0,
                    "comment": "打印时间标题"
                  },
                  {
                    "type": "text",
                    "x": 145,
                    "y": 315,
                    "fontNo": 0,
                    "fontsize": 0,
                    "content": currentTime,
                    "bold": 1,
                    "setmag": 0,
                    "reverse": 0,
                    "comment": "打印时间内容"
                  },
                  // 11. 货物类型 (24px字体)
                  {
                    "type": "text",
                    "x": 405,
                    "y": 310,
                    "fontNo": 0,
                    "fontsize": 0,
                    "content": item.goodsWay == 0 ? '小件' : '整包',
                    "bold": 0,
                    "setmag": 0,
                    "reverse": 0,
                    "comment": "货物类型"
                  }
                ]
    };

    console.log('✅ BLE打印数据生成完成:', blePrintData);
    return blePrintData;
  },
  async printImg(imageData) {
				const testItem = {
					barCode: "DD24111800001001",
					consigneeTel: "138****8888",
					consigneeLinkman: "合肥廖亚玲",
					consignorName: "丁广东",
					consignorTel: "139****9999",
					lineName: "合肥专线",
					shippingPointName: "小叶收货点",
					goodsWay: 0
				};
				// 1. 生成文本模式的打印数据
				console.log('📝 生成文本模式打印数据...');
				const textPrintData = this.generatePrintDataForBLE(testItem);
				console.log('✅ 文本模式数据:', JSON.stringify(textPrintData, null, 2));

				if (imageData) {
					// 将图像数据设置到打印数据中
					for (let index = 0; index < textPrintData.data.length; index++) {
						const elem = textPrintData.data[index];
						var type = elem.type;
						if (type == "image") {
							textPrintData.data[index].imagedata = imageData.data;
							textPrintData.data[index].width = imageData.width; // 使用图片实际宽度
							textPrintData.data[index].height = imageData.height; // 使用图片实际高度
							console.log(textPrintData.data[index], "打印数据");
							console.log(`📏 图片实际尺寸: ${imageData.width}x${imageData.height}`);
							console.log(`📐 图像数据长度: ${imageData.data.length}`);
						}
					}
					try {
						// 执行打印
						const result = snbc.SnbcPrinter.printJob(textPrintData);
						console.log('🖨️ 打印结果:', result);
		
						uni.hideLoading();
						if (result.Result === 0) {
							uni.showToast({
								title: '打印命令发送成功',
								icon: 'success'
							});
						} else {
							uni.showToast({
								title: '打印失败: ' + result.ResultInfo,
								icon: 'error',
								duration: 3000
							});
						}

					} catch (error) {
						console.error('❌ 打印失败:', error);
						// 显示错误提示
						uni.showModal({
							title: '打印失败',
							content: error.message,
							showCancel: false
						});
              wx.hideLoading();

					}

				} else {
					wx.hideLoading();
					wx.showToast({
						title: '获取图像数据失败',
						icon: 'none',
					})
				}
			},
  bindViewTap1: function() {
    var that = this;
    var canvasWidth = 40
    var canvasHeight = 40
    wx.canvasGetImageData({
      canvasId: 'myCanvas',
      x: 0,
      y: 0,
      width: canvasWidth,
      height: canvasHeight,
      success: function (res) {
        that.printImg(res);

        
      },
      complete: function (res) {
      },
      fail: function (res) {
        wx.showToast({
          title: '获取画布数据失败',
          icon: 'none',
        })
      }
    })
  },


  onUnload: function() {
    //搜索完成一定要停止蓝牙搜索功能
    wx.stopBluetoothDevicesDiscovery({
      success: function(res6) {
      }
    })
    //停止搜索后获取本机蓝牙适配器状态
    wx.getBluetoothAdapterState({
      success: function(res7) {
      }
    })
  },
 
  querystatus: function() { 
    snbc.SnbcPrinter.queryStatus({
        callback:(res) => {
          var jsons=res.strResult
          var str
          if(jsons.paper_out==true) str="打印机缺纸"
          else if(jsons.cover_opened==true) str="上盖打开"
          else if(jsons.ready_to_print==true) str="打印机正常"
          wx.showToast({
            title: str,
            icon: 'none',
            duration: 5*1000,
            mask: true
          })
        },
      })  
  },

  base64Tocanvas:function(){
    var that= this;
    var base64Data = '/9j/4AAQSkZJRgABAQEAAAAAAAD/7gAOQWRvYmUAZAAAAAAB/9sAQwAGBAQEBQQGBQUGCQYFBgkLCAYGCAsMCgoLCgoMEAwMDAwMDBAMDg8QDw4MExMUFBMTHBsbGxwfHx8fHx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Und9hTE2hqtS5JEQBtuocGUttA2JK0nJD6O5aTn+9gNKn2J09awtKqEByI7UXRxLl01wRpgURveZIGZ/5jZwHR1goUegdO9ZokZxbsemUtqKy45lxqQyptAKsgBnkOzAZ70Qfpq5/wAZH+6VgHWRoVonb1YqF23QpuQ/LkvTXHKu+hMZCnVlwhDX2aFAZ7AriwCjqH1aUCnNCg6awvzWoH7CPL5SkRWz7KQwyAlbpHYMgn04DkaVdNtw3LXVXzqupbr8pwSRSXsuc+vZkqUBsQgZDJoeg5DZgKlbbbabS00kIbQAlCEgBKUgZAADcBgPrAGAMAYAwHDu2x7Tu6n/AAFx0xioxxnyy6n7RsntbcTktB/dOAwW5ui+mfEmZZtwv0t4HiajywXUpP0XmyhxPrBwCxVtBup1NMk0QXEKtR5KeW9GVUHVNrRmDkUyEpy3YDw2roB1MUGPIg0SoN0OLMUFyQzPDYWpIyBJZC1bsAyUzo6uWrS0zL5u9cle9aI/MkunvHOkkZfwHAbfYGi2ndihLlDpafjwMlVOSedKPfktXsZ9yABgHjAGAMAYAwBgDAGAMAYAwBgDAGAMAYAwH//Z'
    const ctx = wx.createCanvasContext('myCanvas'), //canvas
        fsm = wx.getFileSystemManager(),  //文件管理器
        FILE_BASE_NAME = 'tmp_base64src', //文件名
        format = 'jpg', //文件后缀
      buffer = wx.base64ToArrayBuffer(base64Data), //base 转二进制
      filePath = `${wx.env.USER_DATA_PATH}/www.${format}`; //文件名
  
      fsm.writeFile({ //写文件
        filePath,
        data: buffer,
        encoding: 'binary',
        success(res) {
          wx.getImageInfo({ //读取图片
            src: filePath,
            success: function(res) {

              that.data.canvasWidth=40
              that.data.canvasHeight=40
              ctx.drawImage(res.path, 0, 0, that.data.canvasWidth, that.data.canvasHeight) //画图
              ctx.draw()
            },
            error(res) {

            }
          })
        }
      })
  }

})